package com.onlyphoto.onlymall

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.os.Bundle
import androidx.multidex.MultiDexApplication
import cn.jpush.android.api.JPushInterface
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption

import com.amap.api.location.AMapLocationListener
import com.mcxiaoke.packer.helper.PackerNg
import com.onlyphoto.onlymall.base.BaseActivity
import com.onlyphoto.onlymall.utils.*
import com.onlyphoto.onlymall.widget.CustomRefreshHeader
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import java.util.*
import com.tencent.mm.opensdk.openapi.IWXAPI


/**
 * Created by gaochujia on 2019-05-14.
 */

class MyApplication : MultiDexApplication(), AMapLocationListener {

    private var locCity: String? = ""
    private var district = ""
    private var address = ""
    private var locAddress = ""
    private var lat = 0.0
    private var lon = 0.0
    private var mContext: Context? = null
    private var store: Stack<Activity>? = null

    override fun onCreate() {
        super.onCreate()
        app = this
        ConfigUtil.init(applicationContext)
        store = Stack()
        registerActivityLifecycleCallbacks(SwitchBackgroundCallbacks())
        setAppMarket()
        initRefreshLayout()
        initJPush()
        registerWeixin()
        registerAMapLocation()
        mContext = applicationContext
    }

    private fun setAppMarket(){
        val channelName = if (StringUtil.isBlank(PackerNg.getChannel(this))) "onlyMall" else PackerNg.getChannel(this)
        ConfigUtil.instance.channelName = channelName
    }

    private fun initRefreshLayout(){
        SmartRefreshLayout.setDefaultRefreshHeaderCreater { context, _ -> CustomRefreshHeader(context) }
    }

    private fun initJPush(){
        JPushInterface.setDebugMode(true)    // 测试时开启 设置开启日志,发布时请关闭日志
        JPushInterface.init(this)            // 初始化 JPush
    }

    private fun registerWeixin() {
        api = WXAPIFactory.createWXAPI(this, BuildConfig.WEIXIN_APPID, true)
        // 将该app注册到微信
        api!!.registerApp(BuildConfig.WEIXIN_APPID)
    }

    /**
     * 获取当前的Activity
     *
     * @return
     */
    fun getCurActivity(): BaseActivity<*>? {
        return try {
            store!!.lastElement() as BaseActivity<*>
        } catch (e: Exception) {
            null
        }
    }

    private inner class SwitchBackgroundCallbacks : ActivityLifecycleCallbacks {

        override fun onActivityCreated(activity: Activity, bundle: Bundle?) {}

        override fun onActivityStarted(activity: Activity) {

        }

        override fun onActivityResumed(activity: Activity) {
            if (!store!!.contains(activity)) {
                store!!.add(activity)
            }
        }

        override fun onActivityPaused(activity: Activity) {

        }

        override fun onActivityStopped(activity: Activity) {

        }

        override fun onActivitySaveInstanceState(activity: Activity, bundle: Bundle) {

        }

        override fun onActivityDestroyed(activity: Activity) {
            store!!.remove(activity)
        }
    }

    fun getContext(): Context {
        return mContext!!
    }

    fun isFirstIn(): Boolean {
        return SharePreferenceUtil.getInstance(applicationContext).getIntData(Constants.FIRST_IN, 1) == Constants.IS_FIRST_IN
    }

    companion object {
        @SuppressLint("StaticFieldLeak")
        lateinit var app: MyApplication
        var api: IWXAPI? = null
    }

    /**
     * 位置回调
     */
    private var onPosChanges :ArrayList<OnPosChanged> = ArrayList()

    /**
     * 打开GPS
     *
     * @param lisenter
     * @param status   表示是否进行GPS跟踪
     */

    private var openGps = false
    private var locCount = 0

    //声明AMapLocationClient类对象
    private var mLocationClient: AMapLocationClient? = null

    interface OnPosChanged {
        fun changed(location: AMapLocation)
    }

    fun openGps(listener: OnPosChanged, status: Boolean) {
        openGps = status
        onPosChanges.add(listener)
        setLocOption(1000)
        mLocationClient!!.startLocation()
        //test
    }

    private fun setLocOption(time: Int) {
        val option = AMapLocationClientOption()
        // 设置定位模式
        option.locationMode = AMapLocationClientOption.AMapLocationMode.Battery_Saving
        //设置发起定位请求的间隔时间为5000ms
        option.interval = time.toLong()
        // 返回的定位结果包含地址信息
        option.isNeedAddress = true
        //设置为高精度定位模式
        option.locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
        mLocationClient!!.setLocationOption(option)
    }

    private fun registerAMapLocation() {
        //合规检查
        AMapLocationClient.updatePrivacyShow(app, true, true)
        AMapLocationClient.updatePrivacyAgree(app, true)
        if (mLocationClient == null) {
            mLocationClient = AMapLocationClient(this)
            //设置定位监听
            mLocationClient!!.setLocationListener(this)
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            setLocOption(5000)
        }
    }

    override fun onLocationChanged(amapLocation: AMapLocation?) {
        if (amapLocation != null) {
            if (amapLocation.errorCode == 0) {
                district = amapLocation.district
                address = amapLocation.province + "," + amapLocation.city + "," + district + "," + amapLocation.street
                locAddress = amapLocation.city + district + amapLocation.street + amapLocation.streetNum
                locCity = amapLocation.city
                lon = amapLocation.longitude
                lat = amapLocation.latitude

                if (locCity != null && "" != locCity) {
                    if (!openGps)
                        mLocationClient!!.stopLocation()

                    for(onPosChanged in  onPosChanges){
                        onPosChanged.changed(amapLocation)
                    }
                    onPosChanges.clear()

                } else {
                    locCount++
                    if (locCount >= 4) {
                        if (!openGps)
                            mLocationClient!!.stopLocation()
                        for(onPosChanged in  onPosChanges){
                            onPosChanged.changed(amapLocation)
                        }
                        onPosChanges.clear()
                    }
                }
            } else {
                for(onPosChanged in  onPosChanges){
                    onPosChanged.changed(amapLocation)
                }
                onPosChanges.clear()
            }
        }
    }
}
